package javase.thread;

import java.util.concurrent.CountDownLatch;

/**
 * volatile 线程安全测试
 *
 * @author hck
 */
public class VolatileSafeTest {
    private static volatile int count = 0;
    private static final int THREAD_COUNT = 100;

    private static void increase() {
        count++;
    }

    public static void main(String[] args) throws InterruptedException {

        testIncrease();
//
//        testVal();
    }

    private static void testIncrease() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increase();
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        System.out.println(count);
    }


    private static void testVal() {
        new Thread(() -> {
            setVal(1);
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                System.out.println(getVal());
            }
        }).start();
    }

    private static int value = 0;

    private static int getVal() {
        return value;
    }

    private static void setVal(int val) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = val;
    }
}
